﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.Net.Mail;
using System.Net;
using Common;

namespace TokenGenerator
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnToken_Click(object sender, EventArgs e)
        {
            ElectrosLtdEntities Entity = new ElectrosLtdEntities();
            if ((txtUsername.Text == String.Empty) || (txtPassword.Text == String.Empty) || (txtPinNo.Text == String.Empty))
            {
                lblMsg.Visible = true;
                lblMsg.Text = "Input a username, password and PIN Number!";
            }
            else
            {
                string username = txtUsername.Text.ToLower();
                string password = txtPassword.Text;
                int pin = Convert.ToInt32(txtPinNo.Text);
                User user = Entity.Users.SingleOrDefault(u => u.Username.ToLower() == username && u.Password == password && u.PinNumber == pin);

                if (user != null)
                {
                    lblMsg.Visible = false;
                    Encryption enc = new Encryption();
                    string str = enc.EncryptTripleDES(txtPassword.Text, txtPinNo.Text);
                    lblToken.Visible = true;
                    txtToken.Visible = true;
                    txtToken.Text = str;

                    MailMessage mm = new MailMessage();
                    mm.Priority = MailPriority.High;
                    mm.To.Add(user.Email);
                    mm.Bcc.Add("fabulousfashion00@gmail.com");
                    mm.From = new MailAddress("fabulousfashion00@gmail.com");
                    mm.Subject = "User Details";
                    mm.Body = "Dear " + txtUsername.Text + ", <br/> Your login credentials are as follows";
                    mm.Body += "<br/>Username: " + txtUsername.Text + "<br/>Pin Number: " + txtPinNo.Text + "<br/> Token: " + txtToken.Text;
                    mm.Body += "<br/><br/> Yours faithfully, <br/> Electros Ltd";
                    mm.IsBodyHtml = true;

                    SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
                    client.EnableSsl = true;
                    client.DeliveryMethod = SmtpDeliveryMethod.Network;
                    client.Credentials = new NetworkCredential("fabulousfashion00@gmail.com", "fabfashadmin");
                    client.Send(mm);
                }
                else
                {
                    lblMsg.Visible = true;
                    lblMsg.Text = "Invalid login details";
                }
            }
        }
    }
}
